// com/estore/network/EStoreClient.java
package com.estore.network;

import com.estore.model.Product;
import java.io.*;
import java.net.Socket;
import java.util.Comparator;
import java.util.List;

/**
 * EStore 客户端类，通过 Socket 连接服务器获取商品数据
 */
public class EStoreClient {

    // 服务器地址和端口
    private static final String SERVER_ADDRESS = "localhost";
    private static final int SERVER_PORT = 8888;

    // 购物车：key是商品ID，value是购买数量
    private final java.util.Map<String, Integer> shoppingCart = new java.util.HashMap<>();
    private final java.util.Scanner scanner = new java.util.Scanner(System.in);

    public void start() {
        while (true) {
            showMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    addToCart();
                    break;
                case 3:
                    viewCart();
                    break;
                case 4:
                    System.out.println("感谢使用，再见！");
                    return;
                case 5:
                    showSortedProducts();
                    break;
                case 99:
                    backupData();
                    break;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
    }

    private void showMenu() {
        System.out.println("\n ----欢迎来到商城---- ");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 添加商品到购物车");
        System.out.println("3. 查看购物车");
        System.out.println("4. 退出");
        System.out.println("5. 自定义排序浏览商品");
        System.out.print("请输入您的选择: ");
    }

    /**
     * 通过 Socket 向服务器请求商品列表
     */
    private void browseProducts() {
        Socket socket = null;
        try {
            // 1. 创建 Socket 连接到服务器
            socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
            System.out.println("已连接到服务器：" + SERVER_ADDRESS + ":" + SERVER_PORT);

            // 2. 获取输入输出流
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

            // 3. 发送请求字符串
            out.writeObject("GET_ALL_PRODUCTS");
            out.flush();

            // 4. 读取服务器返回的数据
            Object response = in.readObject();
            if (response instanceof List<?>) {
                @SuppressWarnings("unchecked")
                List<Product> products = (List<Product>) response;
                System.out.println("\n--- 商品列表 ---");
                if (products.isEmpty()) {
                    System.out.println("商店里还没有商品。");
                } else {
                    products.forEach(System.out::println);
                }
            } else {
                System.err.println("服务器返回非预期数据类型：" + response.getClass().getSimpleName());
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("与服务器通信失败：" + e.getMessage());
        } finally {
            // 5. 关闭 Socket
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接失败：" + e.getMessage());
                }
            }
        }
    }

    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = findProductById(productId); // 从服务器查询（暂不实现）
        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("成功将 '" + product.getName() + "' 添加到购物车！");
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        for (java.util.Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
            }
        }
        System.out.println("------------------------------------");
        System.out.printf("总计: ¥%.2f\n", total);
    }

    private Product findProductById(String id) {
        // 简单模拟：实际应从服务器获取
        // 这里仅作为占位，后续可扩展为向服务器发送 GET_PRODUCT_BY_ID 请求
        return null; // TODO: 实现远程查询
    }

    private void showSortedProducts() {
        System.out.println("\n--- 请选择排序方式 ---");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3. 按库存从多到少");
        System.out.print("请输入选择 (1-3): ");

        int choice = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        Comparator<Product> comparator = null;
        switch (choice) {
            case 1:
                comparator = com.estore.service.ProductSorters.BY_PRICE_ASC;
                break;
            case 2:
                comparator = com.estore.service.ProductSorters.BY_PRICE_DESC;
                break;
            case 3:
                comparator = com.estore.service.ProductSorters.BY_STOCK_DESC;
                break;
            default:
                System.out.println("无效选择，将使用默认排序（按ID升序）");
                break;
        }

        // 当前只支持浏览，排序需在客户端完成
        browseProducts(); // 先获取原始数据，再排序
    }

    private void backupData() {
        System.out.println("备份功能暂未实现（客户端无需保存数据）");
    }

    public static void main(String[] args) {
        new EStoreClient().start();
    }
}
